const { src, dest, parallel, series } = require('gulp');
const less = require('gulp-less');
const autoprefixer = require('gulp-autoprefixer');
const cleanCSS = require('gulp-clean-css');
const rename = require("gulp-rename");
const uglify = require('gulp-uglify');
const babel = require('gulp-babel');
const minifyHtml = require("gulp-minify-html");
const del = require('del');
const bs = require("browser-sync");
const watch = require("gulp-watch");

const style = () => {
  return src("src/css/*.less")
    .pipe(less())
    .pipe(autoprefixer())
    .pipe(cleanCSS())
    .pipe(rename({ extname: ".min.css" }))
    .pipe(dest("dist/css"));
};

const js = () => {
  return src("src/js/*.js")
    .pipe(babel())
    .pipe(uglify())
    .pipe(rename({ extname: ".min.js" }))
    .pipe(dest("dist/js"));
};

const html = () => {
  return src("src/index.html")
    .pipe(minifyHtml({
      collapseWhitespace: true,
      minifyCSS: true,
      minifyJS: true
    }))
    .pipe(dest("dist"));
};

const clean = () => {
  return del(["dist"]);
};

const serve = () => {
  // watch(被监视的文件，对应的任务)
  watch("src/index.html", html);
  watch("src/css/*.less", style);
  watch("src/js/*.js", js);

  bs.init({
    notify: false,
    files: "dist/**", // 监视dist下文件的变化
    server: {
      baseDir: "dist",
    }
  })
};

const build = parallel(style, js, html);

const dev = series(clean, build, serve);

module.exports = { dev };
